﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystem;
using ThridGroup.ERP.ProductionSystem;
using Volo.Abp.Application.Dtos;
using System.Collections.Generic;
using System.Linq;

namespace ThridGroup.ERP.Web.Controllers.ProductionSystem
{
    [Route("Procedure")]
    public class ProcedureController : Controller
    {
        private readonly IProcedureServices _procedureServices;

        public ProcedureController(IProcedureServices procedureServices)
        {
            _procedureServices = procedureServices;
        }

        /// <summary>
        /// 工序管理页面
        /// </summary>
        [HttpGet("ProcedureView")]
        public IActionResult ProcedureView()
        {
            return View();
        }

        /// <summary>
        /// 获取工序列表
        /// </summary>
        [HttpPost("List")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> List(QueryProcedureDto input)
        {
            var result = await _procedureServices.GetProcedureList(input);
            return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
        }

        /// <summary>
        /// 添加工序
        /// </summary>
        [HttpPost("Add")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Add(CreateProcedureDto input)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = 1, msg = "请填写必填项" });
            }

            try
            {
                var id = await _procedureServices.AddProcedure(input);
                return Json(new { code = 0, msg = "添加成功", id });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 更新工序
        /// </summary>
        [HttpPost("Update")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Update(CreateProcedureDto input)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = 1, msg = "请填写必填项" });
            }

            try
            {
                var id = await _procedureServices.UpdateProcedure(input);
                return Json(new { code = 0, msg = "修改成功", id });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 删除工序
        /// </summary>
        [HttpPost("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _procedureServices.DeleteProcedure(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取工序详情
        /// </summary>
        [HttpGet("Get")]
        public async Task<IActionResult> Get(int id)
        {
            try
            {
                var data = await _procedureServices.GetProcedureById(id);
                return Json(new { code = 0, msg = "success", data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 批量删除工序
        /// </summary>
        [HttpPost("BatchDelete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchDelete([FromBody] List<int> ids)
        {
            try
            {
                var count = await _procedureServices.BatchDeleteProcedure(ids);
                return Json(new { code = 0, msg = $"成功删除{count}条记录" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "批量删除失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 导出工序列表到Excel
        /// </summary>
        [HttpGet("Export")]
        public async Task<IActionResult> Export([FromQuery] QueryProcedureDto query)
        {
            try
            {
                var fileContents = await _procedureServices.ExportToExcel(query);
                return File(
                    fileContents,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    $"工序列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                );
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "导出失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 生成工序编码
        /// </summary>
        [HttpGet("GenerateProcedureCode")]
        public IActionResult GenerateProcedureCode()
        {
            try
            {
                // 生成格式：GX + 年月日 + 4位随机数
                var today = DateTime.Now;
                string procedureCode = "GX" + today.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();

                return Json(new { code = 0, procedureCode = procedureCode });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "生成工序编码失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 检查工序编码是否已存在
        /// </summary>
        [HttpGet("CheckProcedureCodeExists")]
        public async Task<IActionResult> CheckProcedureCodeExists(string procedureCode)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(procedureCode))
                {
                    return Json(new { code = 1, msg = "工序编码不能为空" });
                }

                // 查询是否存在相同编码
                var query = new QueryProcedureDto
                {
                    ProcedureCode = procedureCode,
                 
                };
                var result = await _procedureServices.GetProcedureList(query);
                bool exists = result.TotalCount > 0;

                return Json(new { code = 0, exists = exists });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查工序编码失败：" + ex.Message });
            }
        }
    }
}
